package com.neu.controller;

import com.google.protobuf.ServiceException;
import com.neu.base.AuthContants;
import com.neu.base.Result;
import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.handler.ServerSentEventsManager;
import com.neu.service.UserService;
import com.neu.utils.RedisUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("/sse")
@Tag(name = "Server-Sent Events")
public class ServerSentEventsController {
    @Autowired
    RedisUtil redisUtils;
    @Autowired
    UserService userService;

    /**
     * 启动 sse 连接
     */
    @GetMapping(value = "connect/{clientKey}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(@PathVariable("clientKey") String clientKey) throws ServiceException {
        String userId = clientKey.split(":")[0];
        User user = userService.getById(userId);
        LoginUser loginUser = (LoginUser) redisUtils.get(AuthContants.REDIS_KEY_AUTH_USER_DETAIL + user.getUsername());
        //System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); //anonymousUser
        if (loginUser != null) {
            return ServerSentEventsManager.create(clientKey);
        }

        throw new ServiceException("Server-Sent Events 连接失败，无法获取用户信息，请登陆后重试");
    }

    /**
     * 关闭 sse 连接
     */
    @PostMapping("close/{clientKey}")
    public Result close(@PathVariable("clientKey") String clientKey) {
        ServerSentEventsManager.close(clientKey);
        return Result.success();
    }

}
